﻿using System.DirectoryServices.AccountManagement;
using System.Linq;
using Microsoft.SharePoint;

namespace Xodeuz.SP.Common
{
    public static class UserAccountHelper
    {
        public struct AD
        {
            /// <summary>
            /// Check if a user with the login name exists in the current domain
            /// </summary>
            public static bool Exists(string loginName)
            {
                using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
                using (UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(context, loginName))
                {
                    return userPrincipal != null ;
                }
            }

            /// <summary>
            /// Is the desired user a member of a specified AD group
            /// </summary>
            public static bool MemberOf(SPUser user, string groupName)
            {
                using(PrincipalContext context = new PrincipalContext(ContextType.Domain))
                using (GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(context, groupName))
                {
                    if (groupPrincipal == null) return false;

                    var members = groupPrincipal.GetMembers(true);

                    return members.OfType<UserPrincipal>().Any(principal => principal.Sid.Value == user.Sid);
                }
            }

        }
    }
}
